<template>
  <view style="display: flex; flex-direction: column; height: 100vh">
    <u-sticky>
      <u-navbar back-text=" " title="进/撤场" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
      ></xmInfo>
    </u-sticky>

	<view style="flex: 1;  overflow: scroll">
    <view class="cu-card dynamic">      
      <view
        class="margin jc-flex"
        v-if="Object.keys(jinCheChangData).length !== 0"
      >
        <view class="cu-list menu sm-border margin-top margin-bottom-sm">
          <view class="cu-item">
            <view class="content">
              <text class="text-grey text-xxl text-bold">进场</text>
            </view>
            <dictLabel
              :value="jinCheChangData.state ? jinCheChangData.state : 0"
              dict-type="zf_proj_jcsg_status"
              :dict-list="dictList"
              :fontSize="'36rpx'"
            ></dictLabel>
          </view>
        </view>
        <view class="cu-form-group">
          <view class="text-xl">通知进场日期</view>
          <view class="text-xl">{{ jinCheChangData.predate }}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">确认进场日期</view>
          <view class="title">{{ jinCheChangData.approachdate }}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">确认进场现场图片</view>
        </view>
        <view class="cu-form-group">
          <js-uploadfile
            maxCount="0"
            v-if="uploadFile"
            :biz-key="jinCheChangData.id"
            biz-type="pmApproachEN_image"
            :deletable="false" 
            customBtn="false"
          ></js-uploadfile>
        </view>
        <view class="cu-list menu sm-border margin-top margin-bottom-sm">
          <view class="cu-item">
            <view class="content">
              <text class="text-grey text-xxl text-bold">撤场</text>
            </view>
          </view>
        </view>
        <view>
          <view class="cu-form-group margin-top">
            <view class="text-xl">通知撤场日期</view>
            <view class="text-xl">{{
              jinCheChangData.prewithdrawdate
            }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">确认撤场日期</view>
            <view class="title">{{ jinCheChangData.withdrawdate }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">确认撤场现场图片</view>
          </view>
          <view class="cu-form-group">
            <js-uploadfile
              maxCount="0"
              v-if="uploadFile"
              :biz-key="jinCheChangData.id"
              biz-type="pmApproachEX_image"
              :deletable="false" 
              customBtn="false"
            ></js-uploadfile>
          </view>
        </view>
      </view>
      <view v-else>
        <u-empty
          mode="data"
          text="当前项目处于施工准备阶段，无进/撤场信息"
        ></u-empty>
      </view>
    </view>
    <view style="height: 80px"></view>
    <view
      class="btn-group cu-bar foot"
      v-if="
        jinCheChangData.state == vuex_config.STATUS_NOT ||
        jinCheChangData.state == vuex_config.STATUS_ENTZ ||
        jinCheChangData.state == vuex_config.STATUS_EN ||
        jinCheChangData.state == vuex_config.STATUS_EXTZ
      "
    >


      <button
        class="cu-btn text-green line-green shadow"
        @tap="showModal(status)"
        v-if="(jinCheChangData.state == vuex_config.STATUS_NOT || jinCheChangData.state == vuex_config.STATUS_ENTZ)  && jcqrFlag"
      >
        确认进场
      </button>
      <button
        class="cu-btn bg-blue shadow-blur"
        @click="DateChange(status)"
        v-if="jinCheChangData.state == vuex_config.STATUS_EN   &&(jcFlag || ccFlag)"
      >
        撤场通知
      </button>
      <button
        class="cu-btn text-green line-blue shadow"
        @tap="showModal(status)"
        v-if="jinCheChangData.state >= vuex_config.STATUS_EXTZ  && ccqrFlag"
      >
        确认撤场
      </button>
    </view>


    <view
      class="btn-group cu-bar foot"
      v-else-if="Object.keys(jinCheChangData).length == 0 && (this.jcFlag || this.ccFlag)"
    >
      <button class="cu-btn bg-green shadow-blur" @click="DateChange(status)">
        进场通知
      </button>
    </view>
    <!-- 使用uView的u-popup组件作为弹出容器 -->
    <!-- <u-popup v-model="isPopupShow" @close="closeDatePicker">
			
		</u-popup> -->
    <u-picker
      mode="time"
      v-model="isPopupShow"
      :params="params"
      :start-year="startYear"
      :end-year="endYear"
      :default-time="defaultTime"
      @confirm="confirmPicker"
    ></u-picker>
    <!--  -->
    <bottom-form
      :modalName="modalName"
      @modalNameEmit="modalNameEmit"
      :bizType="bizType"
      :bizKey="bizKey"
      :status="jinCheChangData.state"
      @fdData="fdData"
      v-if="modalName == 'bottomModal'"
    ></bottom-form>
  </view>
  </view>
</template>

<script>
import bottomForm from "./bottomForm.vue"
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    bottomForm,
    xmInfo,
    dictLabel,
  },
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      currentImageUrl: "",
      jinChangNotify: true,
      jinChangStatus: false,
      isPopupShow: false,
      selectedDate: new Date(), // 当前日期
      params: {
        year: true,
        month: true,
        day: true,
      },
      startYear: 1950, // 开始年份
      endYear: 2050, // 结束年份
      defaultTime: '', // 默认时间
      startTime: 0, // 开始天数配置
      modalName: null,
      jinChangData: {
        noticeDta: "2024-03-11",
        confirmData: "2024-03-12",
      },
      jinCheChangData: {},
      itemContent: {},
      dictList: [],
      bizType: "",
      bizKey: "",
      uploadFile:false,
      status: "", //状态判断,
      jcFlag: hasPermission('proj:enex:pmApproach:sendEn'),
      ccFlag: hasPermission('proj:enex:pmApproach:sendEx'),
      jcqrFlag: hasPermission('proj:enex:pmApproach:validEn'),
      ccqrFlag: hasPermission('proj:enex:pmApproach:validEx'),
      startTime: '',
    };
  },
  created() {
    console.log(uni.$u.config.v);
  },
  onLoad(e) {
    console.log(e,'e.item===')
    if (typeof e.item !== "undefined") {
      
      try {
        this.itemContent = JSON.parse(e.item);
        console.log(this.itemContent);
        this.getDictList();
        this.getJinCheChang();

        this.uploadFile = true;
        this.status = e.status;
        console.log(this.status,'status----');
        setTimeout(() => {
          this.bizKey = this.jinCheChangData.id;
        }, 500);
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
  },

  methods: {
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    fdData(e) {
      const { fdData, approachdate } = e;
      console.log(this.jinCheChangData.state,'state');
      if (this.jinCheChangData.state == 4) {
        const params = {
          id: this.jinCheChangData.id,
          name: this.itemContent.projectname,
          pcode: this.itemContent.projectno,
          withdrawdate: approachdate,
          ...fdData,
        };
        this.$u.api.zfgs.enexPmApproachValidEx(params).then((res) => {
          if (res.result == "true") {
            this.getJinCheChang();
            this.$u.toast(res.message);
          } else {
            this.$u.toast(res.message);
          }
        });


      } else {
        const params = {
          id: this.jinCheChangData.id,
          name: this.itemContent.projectname,
          pcode: this.itemContent.projectno,
          approachdate: approachdate,
          ...fdData,
        };
        this.$u.api.zfgs.enexPmApproachValidEn(params).then((res) => {
          if (res.result == "true") {
            this.getJinCheChang();
            this.$u.toast(res.message);
          } else {
            this.$u.toast(res.message);
          }
        });
      }
    },
    getDictList() {
      this.$u.api
        .dictListData({ dictType: "zf_proj_jcsg_status" })
        .then((res) => {
          this.dictList = res;
        });
    },
    getJinCheChang() {
      this.$u.api.zfgs
        .enexPmApproachListData({
          name: this.itemContent.projectname,
          pcode: this.itemContent.projectno,
        })
        .then((res) => {
          if (res.list && res.list.length > 0) {
            this.jinCheChangData = res.list[0];
            console.log(this.jinCheChangData,'this.jinCheChangData');
            this.uploadFile = false
            setTimeout(() => {
              this.uploadFile = true
            }, 500);
          }
        });
    },
    // 点击DateChange，弹出日期选择器
    DateChange(status) {
      // 根据状态判断是否需要获取配置
      if (this.jinCheChangData.state == 2 || this.jinCheChangData.state == 3) {
        // 根据状态选择不同的配置key
        let configKey = '';
        if (this.jinCheChangData.state == 2) {
          configKey = 'zf:withdrawal:days:tz'; // 撤场通知
        } else if (this.jinCheChangData.state == 3) {
          configKey = 'zf:withdrawal:days:qr'; // 撤场确认
        }

        // 获取配置，然后设置日期范围
        this.$u.api.zfgs.getConfigValue({
          configKey: configKey
        }).then((res)=>{
          this.startTime = parseInt(res) || 0; // 确保是数字类型
          this.setDateRange(status);
          this.isPopupShow = true; // 显示日期选择器
        }).catch((error) => {
          console.error('获取配置失败:', error);
          this.startTime = 0; // 默认值
          this.setDateRange(status);
          this.isPopupShow = true; // 显示日期选择器
        });
      } else {
        // 其他状态不设置日期限制，直接使用默认值
        this.startTime = 0;
        this.setDateRange(status);
        this.isPopupShow = true; // 显示日期选择器
      }
    },

    // 设置日期选择范围
    setDateRange(status) {
      const today = new Date();
      const currentYear = today.getFullYear();

      // 设置年份范围
      this.startYear = currentYear - 1; // 允许选择去年的日期
      this.endYear = currentYear + 10; // 可选择未来5年

      if (this.jinCheChangData.state == 2) {
        // 撤场通知：开始日期是当前日期往前推startTime天
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - this.startTime);

        // 如果有进场日期，需要考虑进场日期的限制
        if (this.jinCheChangData.approachdate) {
          const approachDate = new Date(this.jinCheChangData.approachdate);
          // 取较晚的日期作为默认时间（不能早于进场日期）
          const defaultDate = startDate > approachDate ? startDate : approachDate;
          this.defaultTime = this.formatDate(defaultDate);
        } else {
          // 没有进场日期，使用计算出的开始日期
          this.defaultTime = this.formatDate(startDate);
        }
      } else if (this.jinCheChangData.state == 3) {
        // 撤场确认：开始日期是当前日期往前推startTime天
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - this.startTime);

        // 如果有撤场通知日期，需要考虑撤场通知日期的限制
        if (this.jinCheChangData.prewithdrawdate) {
          const preWithdrawDate = new Date(this.jinCheChangData.prewithdrawdate);
          // 取较晚的日期作为默认时间（不能早于撤场通知日期）
          const defaultDate = startDate > preWithdrawDate ? startDate : preWithdrawDate;
          this.defaultTime = this.formatDate(defaultDate);
        } else {
          // 没有撤场通知日期，使用计算出的开始日期
          this.defaultTime = this.formatDate(startDate);
        }
      } else {
        // 其他状态（如进场通知）：默认选择今天，不设置日期限制
        this.defaultTime = this.formatDate(today);
      }

      console.log('设置日期范围:', {
        startYear: this.startYear,
        endYear: this.endYear,
        defaultTime: this.defaultTime,
        startTime: this.startTime,
        state: this.jinCheChangData.state
      });
    },

    // 格式化日期为字符串
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 验证选择的日期是否合法
    validateSelectedDate(selectedDate) {
      const selected = new Date(selectedDate.year, selectedDate.month - 1, selectedDate.day);

      // 只有状态为2或3时才进行日期范围限制验证
      if (this.jinCheChangData.state == 2 || this.jinCheChangData.state == 3) {
        // 计算允许的最早日期（当前日期往前推startTime天）
        const earliestDate = new Date();
        earliestDate.setDate(earliestDate.getDate() - this.startTime);

        // 检查选择的日期不能早于允许的最早日期
        if (selected < earliestDate.setHours(0, 0, 0, 0)) {
          this.$u.toast(`选择的日期不能早于${this.formatDate(earliestDate)}`);
          return false;
        }

        // 如果是撤场通知（状态2），还需要检查不能早于进场日期
        if (this.jinCheChangData.state == 2 && this.jinCheChangData.approachdate) {
          const approachDate = new Date(this.jinCheChangData.approachdate);
          if (selected < approachDate.setHours(0, 0, 0, 0)) {
            this.$u.toast('撤场日期不能早于进场日期');
            return false;
          }
        }

        // 如果是撤场确认（状态3），还需要检查不能早于撤场通知日期
        if (this.jinCheChangData.state == 3 && this.jinCheChangData.prewithdrawdate) {
          const preWithdrawDate = new Date(this.jinCheChangData.prewithdrawdate);
          if (selected < preWithdrawDate.setHours(0, 0, 0, 0)) {
            this.$u.toast('撤场确认日期不能早于撤场通知日期');
            return false;
          }
        }
      }

      return true;
    },

    closeDatePicker() {
      this.isPopupShow = false; // 关闭日期选择器
    },
    confirmPicker(e) {
      console.log(e);

      // 验证选择的日期是否合法
      if (!this.validateSelectedDate(e)) {
        return; // 如果日期不合法，直接返回，不执行后续操作
      }

      this.jinChangStatus = true;
      this.jinChangNotify = false;
      console.log(this.jinCheChangData, "jinCheChangData");
      if (this.jinCheChangData.state == 2) {
        this.$u.api.zfgs
          .enexPmApproachSengExMsg({
            id: this.jinCheChangData.id,
            pcode: this.itemContent.projectno,
            name: this.itemContent.projectname,
            prewithdrawdate: e.year + "-" + e.month + "-" + e.day,
          })
          .then((res) => {
            console.log(res);
            if (res.result == "true") {
              this.getJinCheChang();
              this.$u.toast(res.message);
            } else {
              this.$u.toast(res.message);
            }
          });
      } else {
        this.$u.api.zfgs
          .enexPmApproachSengEnMsg({
            pcode: this.itemContent.projectno,
            name: this.itemContent.projectname,
            predate: e.year + "-" + e.month + "-" + e.day,
          })
          .then((res) => {
            console.log(res, "res");
            if (res.result == "true") {
              this.getJinCheChang();
              this.$u.toast(res.message);
            } else {
              this.$u.toast(res.message);
            }
          });
      }

      // this.$u.toast("通知成功");
    },
    showModal(status) {
      if (this.jinCheChangData.state == this.vuex_config.STATUS_EXTZ) {
        this.bizType = "pmApproachEX_image";
      } else {
        this.bizType = "pmApproachEN_image";
      }

      this.modalName = "bottomModal";
    },

    modalNameEmit(e) {
      this.modalName = e;
    },
  },
};
</script>

<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
.text-grey {
  color: #000;
}
.jc-flex {
  border-radius: 60rpx;
  font-size: 30rpx;
}
</style>
